package chis.dip.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import android.content.res.AssetManager;
import android.os.Environment;

public class ReadTextFile {
	
	public String readText(String fileName, AssetManager assetManager) {
		String text = null;
		InputStream inputStream = null;
		try {
			inputStream = assetManager.open(fileName);
			 text = loadTextFile(inputStream);
			return text;
			//textView.setText(text);
		} catch (IOException e) {
			//textView.setText("Couldn't load file");
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					//textView.setText("Couldn't close file");
				}
			}
		}
		return text;
	}

	public String loadTextFile(InputStream inputStream) throws IOException {
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		byte[] bytes = new byte[4096];
		int len = 0;
		while ((len = inputStream.read(bytes)) > 0) {
			byteStream.write(bytes, 0, len);
		}
		return new String(byteStream.toByteArray(), "UTF8");
	}

//	public String readText(String fileName) {
//
//		String text = null;
//		String state = Environment.getExternalStorageState();
//		if (!state.equals(Environment.MEDIA_MOUNTED)) {
//			//textView.setText("No external storage mounted");
//		} else {
//			File externalDir = Environment.getExternalStorageDirectory();
//			File textFile = new File(externalDir.getAbsolutePath() + File.separator + fileName);
//			try {
//				//writeTextFile(textFile, "This is a text. Roger");
//				 text = read(textFile);
//
//			} catch (IOException e) {
//				return null;			
//			}
//		}
//
//		return text;
//	}
//
//	private String read(File file) throws IOException {
//		BufferedReader reader = new BufferedReader(new FileReader(file));
//		StringBuilder text = new StringBuilder();
//		String line;
//		while ((line = reader.readLine()) != null) {
//			text.append(line);
//			//text.append("\n");
//		}
//		reader.close();
//		return text.toString();
//	}

}
